# -*- coding: utf-8 -*-

from google.appengine.ext import db

class Propos(db.Model):
  content = db.StringProperty(multiline=True)
  tags = db.ListProperty(unicode)
  #subpropos = db.SelfReferenceProperty()
  subpropos = db.ListProperty(db.Key)
  parentpropos = db.ListProperty(db.Key)
  createdate = db.DateTimeProperty(auto_now_add=True)
  modifydate = db.DateTimeProperty(auto_now=True)

  def updateSimilar(self):
    #update all similar relation
    allpropos = Propos.all()
    for pp in allpropos:
      #a bug of the same
      if self.key() == pp.key():
        continue
      tmpl = []
      tmpl.append(self.key())
      tmpl.append(pp.key())
      value = Propos.getSimValue(self,self.content,pp.content)
      ps = ProposSimilar(proposlist=tmpl,simvalue=value)
      ps.put()

  def deleteallSimilar(self):
    #delete all relation about this Propose
    #ditems = db.GqlQuery("SELECT * FROM ProposSimilar WHERE propose1 = :1 OR propose2 = :2",
    #                     self.key(),self.key())
    ditems = ProposSimilar.all()
    
    for item in ditems:
      try:
        nPos =  item.proposlist.index(self.key())
      except:
        nPos = -1;
      if nPos != -1:
          item.delete()
        
  def getSimValue(self,str1,str2):
    n = 0
    for i in range(0,len(str1),1):
      try:
        nPos = str2.index(str1[i])
      except:
        nPos = -1
      if nPos != -1:
        n = n + 1
    return (float)(n)/(len(str1))
  
  @staticmethod
  def fillParent(self):
    ps = Propose.all()
    for item in ps:
      for subitem in ps.subpropos:
        subentity = db.get(subitem)
        subentity.parentpropos.append(item.key())
        subentity.put()
    
class ProposSimilar(db.Model):
  #propose1 = db.ReferenceProperty(Propos)
  #propose2 = db.ReferenceProperty(Propos)
  proposlist = db.ListProperty(db.Key)
  simvalue = db.FloatProperty()
  
"""
  def __init__(self,propos1,propos2):
    self.proposlist.append(propos1.key())
    self.proposlist.append(propos2.key())
    self.simvalue = getSimValue.getSimValue(self,propos1.content,propos2.content)

  def getSimValue(self,str1,str2):
    n = 0
    for i in range(0,len(str1),1):
      nPos = str2.index(str1[i])
      if nPos != -1:
        n = n + 1
    return (float)(n)/(len(str1))         
"""
